/**
 * 单个收费类型
 */
import React, { Component } from 'react';
import { Button, Input, Select, Icon, Popconfirm, Checkbox, InputNumber, message } from 'antd';
import CommandEdit from './commandEdit';

const Option = Select.Option;
const defatltClock = {
	isClockCorrect: 1,
	clockCorrectDatapoint: '请选择',
	errorRange: 0,
	calculateValue: 1
};
const defatltClock1 = {
	isClockCorrect: 0,
	clockCorrectDatapoint: '请选择',
	errorRange: 0,
	calculateValue: 1
};

export const defaultValue = {
	name: '',
	normal: null,
	special: {
		displayUnit: '',
		multiplyValue: '',
		name: '',
		type: 'unit',
		min: 0,
		max: 50,
		step: 1,
		dataPointUnit: '小时'
	},
	deviceModel: null,
	...defatltClock1
};

const styles = {
	input: {
		display: 'inline-block',
		width: '4em',
		margin: '0 0.5em'
	},
	select: {
		width: '14em',
		marginRight: '0.5em'
	},
	name: {
		display: 'inline-block',
		width: '12em'
	},
	m: {
		marginRight: '27px'
	},
	h: {
		marginBottom: '0.5em'
	},
	title: {
		fontSize: '18px'
	},
	box: {
		border: '1px solid #ccc',
		borderRadius: '4px',
		marginBottom: '1em'
	},
	save: {
		marginTop: '0.5em',
		textAlign: 'right'
	},
	margin: {
		marginRight: '0.5em'
	},
	span: {
		margin: '0 0.8em'
	},
	icon: {
		fontSize: '16px',
		float: 'right',
		margin: '0 0.4em'
	}
};

class FeeItem extends Component {
	constructor(props, context) {
		super(props, context);
		this.state = {
			...defaultValue,
			...props.data,
			edit: !props.data.id
		};
	}

	componentWillReceiveProps(nextProps) {
		if (nextProps.data !== this.props.data) {
			this.setStateFromProps(nextProps);
		}
	}

	setStateFromProps(props) {
		this.setState(Object.keys(defaultValue).reduce((p, k) => {
			p[k] = props.data[k];
			return p;
		}, {}));
	}

	inputChange = e => {
		const { special } = this.state;
		const { name, value } = e.target;
		if (name === 'name') this.setState({ name: value });
		else {
			this.setState({ special: { ...special, [name]: value } });
		}
	}

	specialChange = name => {
		const { dataPoint } = this.props;
		const point = dataPoint.find(d => d.identityName === name);
		let valueLimit = null;
		try {
			valueLimit = JSON.parse(point.valueLimit);
		} catch (error) {
			valueLimit = {
				min: 0,
				max: 50
			};
		}
		const newSpecial = {
			displayUnit: '',
			multiplyValue: '',
			name,
			type: point.dataType,
			min: valueLimit.min,
			max: valueLimit.max,
			step: 1,
			dataPointUnit: ''
		};
		this.setState({ special: { ...newSpecial } });
	}

	delete = () => {
		const { data } = this.props;
		this.props.delete(data.id);
	}

	save = () => {
		const { data, save } = this.props;
		const { special, name, errorRange, calculateValue, clockCorrectDatapoint, isClockCorrect } = this.state;
		const normal = this.normal.getValue();
		const deviceModel = this.deviceModel.getValue();
		const refDataPoint = this.refDataPoint.getValue();
		const clock = isClockCorrect ? { errorRange, calculateValue, clockCorrectDatapoint } : {};
		const newData = {
			name, special, normal, deviceModel, refDataPoint,
			isClockCorrect,
			...clock,
			id: data.id
		};
		if (!name) return message.error('名称为必填项');
		if (!special.multiplyValue || !special.name || !special.step) return message.error('设置换算单位');
		if (isClockCorrect && !clockCorrectDatapoint) {
			return message.error('请选择换算数据点单位');
		}
		save(newData);
		this.setState({ edit: false });
	}

	cancel = () => {
		const { data, cancel, index } = this.props;
		this.setStateFromProps(this.props);
		if (data.id) this.setState({ edit: false });
		else cancel(index);
	}

	render() {
		const {
			normal, special, deviceModel, edit, name, id, refDataPoint,
			clockCorrectDatapoint, calculateValue, errorRange, isClockCorrect
		} = this.state;
		const { dataPoint, data } = this.props;
		const uintWritableDataPoint = dataPoint.filter(d => d.dataType.indexOf('uint') === 0 && d.readWriteType === 'status_writable');
		return edit ? (
			<div style={styles.box} className="pad1">
				<div style={styles.h}>
					<label>收费类型：</label>
					<Input style={styles.name} onChange={this.inputChange} name="name" value={name} />
				</div>
				<div>
					<span style={styles.m}>显示单位：</span>
					<span>换算数据点单位：</span>
				</div>
				<div style={styles.h}>
					1<Input placeholder="单位" style={styles.input} value={special.displayUnit} onChange={this.inputChange} name="displayUnit" />
					= <Input placeholder="数值" value={special.multiplyValue} style={styles.input} onChange={this.inputChange} name="multiplyValue" />
					<Select onChange={this.specialChange} value={special.name} style={styles.select}>
						{uintWritableDataPoint.map(d => <Option value={d.identityName}>{d.identityName}</Option>)}
					</Select>
				</div>
				<div style={styles.h}>
					下发控制指令数据点：<br />
					<CommandEdit dataPoint={dataPoint} value={normal} ref={d => d ? this.normal = d : null} />
				</div>
				<div style={styles.h}>
					设备切换收费类型下发数据点：<br />
					<CommandEdit dataPoint={dataPoint} value={deviceModel} ref={d => d ? this.deviceModel = d : null} />
				</div>
				<div style={styles.h}>
					设备续费数据点<br />
					<CommandEdit needInput={false} needMulti={false} dataPoint={dataPoint} value={refDataPoint} ref={d => d ? this.refDataPoint = d : null} />
				</div>
				<hr />
				<div style={styles.h}>
					<Checkbox
						checked={!!isClockCorrect}
						style={styles.h}
						onChange={e => this.setState(e.target.checked ? { ...defatltClock } : { ...defatltClock1 })}
					>
						是否需要时钟校准
					</Checkbox>
					{
						isClockCorrect ? (
							<div>
								<div style={styles.h}>
									换算数据点单位：
									<Select onChange={v => this.setState({ clockCorrectDatapoint: v })} value={clockCorrectDatapoint} style={styles.select}>
										{uintWritableDataPoint.map(d => <Option value={d.identityName}>{d.identityName}</Option>)}
									</Select>
									= <InputNumber placeholder="数值" value={calculateValue} style={styles.input} onChange={v => this.setState({ calculateValue: v })} />
									分钟
								</div>
								<div style={styles.h}>
									时钟校准允许误差范围：
									<InputNumber placeholder="请输入整数数值" value={errorRange} onChange={v => this.setState({ errorRange: v })} />
								</div>
							</div>
						) : null
					}
				</div>
				<hr />
				<div style={styles.save}>
					<Button onClick={this.cancel} style={styles.margin}>取消</Button>
					<Button onClick={this.save} type="primary">保存</Button>
				</div>
			</div>
		) : (
				<div style={styles.box}>
					<div style={styles.h} className="table-thead pad1">
						<label>收费类型：</label>
						<span>{data.name}</span>
						<Popconfirm title="确定删除当前收费类型吗？" onConfirm={this.delete} okText="确定" cancelText="取消">
							<Icon type="delete" className="cursor" style={styles.icon} />
						</Popconfirm>
						<Icon type="edit" className="cursor" style={styles.icon} onClick={() => this.setState({ edit: true })} />
					</div>
					<div className="pad1">
						<div>
							<span style={styles.m}>显示单位：</span>
							<span>换算数据点单位：</span>
						</div>
						<div style={styles.h}>
							<span style={styles.span}>1</span>
							<span style={styles.span}>{data.special.displayUnit}</span>
							<span style={styles.span}>=</span>
							<span style={styles.span}>{data.special.multiplyValue}</span>
							<span style={styles.span}>{data.special.name}</span>
						</div>
						<div style={styles.h}>
							下发控制指令数据点：{JSON.stringify(data.normal)}
						</div>
						<div style={styles.h}>
							设备切换收费类型下发数据点：{JSON.stringify(data.deviceModel)}
						</div>
						<div style={styles.h}>
							设备续费数据点：{data.refDataPoint}
						</div>
						<div style={styles.h}>
							是否需要时钟校准：<Checkbox checked={!!data.isClockCorrect} /><br />
							{
								isClockCorrect ? <div>
									换算数据点单位：{isClockCorrect} = {calculateValue} 分钟<br />
									时钟校准允许误差范围：{errorRange}
								</div> : null
							}
						</div>
					</div>
				</div>
			);
	}
}

export default FeeItem;
